﻿using System;
using System.Data;
using System.IO;
using System.Reflection;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using AnyOffice.Components;
using log4net;
namespace AnyOffice.general.file_folder
{
    public partial class index : ModulePage
    {
        private static ILog log= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                string str = (Request.QueryString["path"] != null) ? Request.QueryString["path"].ToString() : "/";
                this.ViewState["CurrentPath"] = str;
                this.GetFileInfo(str);
                this.btnDelete.Attributes.Add("onclick", "return delete_confirm();");
                this.btnMove.Attributes.Add("onclick", "return move_confirm();");
            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                string str = "/attachment/file_folder/" + HttpContext.Current.User.Identity.Name;
                string str2 = "";
                foreach (RepeaterItem item in this.rptInfo.Items)
                {
                    HtmlInputCheckBox box = (HtmlInputCheckBox)item.FindControl("PathId");
                    if ((box != null) && box.Checked)
                    {
                        str2 = box.Value.Replace("../", "");
                        if (str2.StartsWith("DIR"))
                        {
                            str2 = str2.Substring(3, str2.Length - 3);
                            new DirectoryInfo(Server.MapPath(str + str2)).Delete(true);
                        }
                        if (str2.StartsWith("FILE"))
                        {
                            str2 = str2.Substring(4, str2.Length - 4);
                            new FileInfo(Server.MapPath(str + str2)).Delete();
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("", exception);
                }
            }
            this.checkAll.Checked = false;
            this.GetFileInfo(this.ViewState["CurrentPath"].ToString());
        }

        protected void btnFolderAttribute_Click(object sender, EventArgs e)
        {
            Response.Redirect("changefolder.aspx?foldername=" + Server.UrlEncode(this.currentFolder.SelectedValue));
        }

        protected void btnMove_Click(object sender, EventArgs e)
        {
            try
            {
                string str = "/attachment/file_folder/" + HttpContext.Current.User.Identity.Name;
                string path = str + this.destFolder.SelectedValue;
                if (path.EndsWith("/"))
                {
                    path = path.Substring(0, path.Length - 1);
                }
                string str3 = "";
                foreach (RepeaterItem item in this.rptInfo.Items)
                {
                    HtmlInputCheckBox box = (HtmlInputCheckBox)item.FindControl("PathId");
                    if ((box != null) && box.Checked)
                    {
                        str3 = box.Value.Replace("../", "");
                        if (str3.StartsWith("DIR"))
                        {
                            str3 = str3.Substring(3, str3.Length - 3);
                            DirectoryInfo info = new DirectoryInfo(Server.MapPath(str + str3));
                            if (Server.MapPath(path).StartsWith(info.FullName))
                            {
                                this.pnlMain.Visible = false;
                                this.litMessage.Text = base.ShowError("不允许将一个目录移动到它的子目录下面！", "index.aspx?path=" + Server.UrlEncode(this.ViewState["CurrentPath"].ToString()));
                                return;
                            }
                            if (info.Parent.FullName != Server.MapPath(path))
                            {
                                if (Directory.Exists(Server.MapPath(path + "/" + info.Name)))
                                {
                                    this.pnlMain.Visible = false;
                                    this.litMessage.Text = base.ShowError("移动操作出错：已有同名目录存在！", "index.aspx?path=" + Server.UrlEncode(this.ViewState["CurrentPath"].ToString()));
                                    return;
                                }
                                try
                                {
                                    info.MoveTo(Server.MapPath(path + "/" + info.Name));
                                }
                                catch (Exception)
                                {
                                }
                            }
                        }
                        if (str3.StartsWith("FILE"))
                        {
                            str3 = str3.Substring(4, str3.Length - 4);
                            FileInfo info2 = new FileInfo(Server.MapPath(str + str3));
                            if (info2.Directory.FullName == Server.MapPath(path))
                            {
                                continue;
                            }
                            if (File.Exists(Server.MapPath(path + "/" + info2.Name)))
                            {
                                this.pnlMain.Visible = false;
                                this.litMessage.Text = base.ShowError("移动操作出错：已有同名文件存在！", "index.aspx?path=" + Server.UrlEncode(this.ViewState["CurrentPath"].ToString()));
                                return;
                            }
                            try
                            {
                                info2.MoveTo(Server.MapPath(path + "/" + info2.Name));
                                continue;
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("", exception);
                }
            }
            this.checkAll.Checked = false;
            this.GetFileInfo(this.ViewState["CurrentPath"].ToString());
        }

        protected void btnNewFile_Click(object sender, EventArgs e)
        {
            Response.Redirect("newfile.aspx?parent_folder=" + Server.UrlEncode(this.currentFolder.SelectedValue));
        }

        protected void btnNewFloder_Click(object sender, EventArgs e)
        {
            Response.Redirect("newfolder.aspx?parent_folder=" + Server.UrlEncode(this.currentFolder.SelectedValue));
        }

        protected void currentFolder_SelectedIndexChanged(object sender, EventArgs e)
        {
            Response.Redirect("index.aspx?path=" + Server.UrlEncode(this.currentFolder.SelectedValue));
        }

        public string formatSize(long size)
        {
            return StringHelper.FormatSize(size);
        }    

        public string OfficeMenu(string path)
        {
            string str = string.Empty;
            if (((!path.ToLower().EndsWith("doc") && !path.ToLower().EndsWith("xls")) && (!path.ToLower().EndsWith("ppt") && !path.ToLower().EndsWith("docx"))) && (!path.ToLower().EndsWith("xlsx") && !path.ToLower().EndsWith("pptx")))
            {
                return str;
            }
            return "<input type=\"button\" value=\"阅读\" class=\"SmallButton\" onClick=\"window.open('read.aspx?filename=" + Server.UrlEncode(path) + "',null,'menubar=0,toolbar=0,status=1,scrollbars=1,resizable=1');\">";
        }


        private void GetFileInfo(string currentPath)
        {
            string str = "/";
            if (currentPath.LastIndexOf("/") > 0)
            {
                str = currentPath.Substring(0, currentPath.LastIndexOf("/"));
            }
            this.ViewState["ParentPath"] = str;
            if (currentPath != "/")
            {
                this.pnlJumpParent.Visible = true;
            }
            DirectoryUtility utility = new DirectoryUtility(currentPath);
            this.rptInfo.DataSource = utility.DtbInfo;
            this.rptInfo.DataBind();
            LiteUtility utility2 = new LiteUtility();
            DataTable dtbDirectory = utility2.GetDtbDirectory();
            this.currentFolder.DataSource = dtbDirectory;
            this.currentFolder.DataTextField = "path";
            this.currentFolder.DataValueField = "path";
            this.currentFolder.DataBind();
            if (this.currentFolder.Items.FindByValue(currentPath) != null)
            {
                this.currentFolder.Items.FindByValue(currentPath).Selected = true;
            }
            this.destFolder.DataSource = dtbDirectory;
            this.destFolder.DataTextField = "path";
            this.destFolder.DataValueField = "path";
            this.destFolder.DataBind();
            this.litStatic.Text = "共 " + utility.FileCount.ToString() + " 个文件, " + this.formatSize(utility.TotalSize);
            long num2 = utility2.UsedSize();
            UserCache cache = new UserCache();
            if (cache.FolderCapacity != 0)
            {
                long num3 = ((cache.FolderCapacity * 1024) * 1024) - num2;
                string str2 = (Convert.ToSingle(num2) / ((float)((cache.FolderCapacity * 1024) * 1024))).ToString("p");
                string str3 = Convert.ToString((long)((num2 * 100L) / ((long)((cache.FolderCapacity * 1024) * 1024))));
                this.ViewState["Percent"] = str3;
                this.litWholeStatic.Text = "总空间" + cache.FolderCapacity.ToString() + "M：已用" + this.formatSize(num2) + "（" + str2 + "），剩余" + this.formatSize(num3);
            }
            else
            {
                this.ViewState["Percent"] = 1;
                this.litWholeStatic.Text = "总空间不限制：已用" + this.formatSize(num2);
            }
        }
        
        public string Thumb(string path, string upDownMaximum)
        {
            string str = string.Empty;
            if ((!path.ToLower().EndsWith("gif") && !path.ToLower().EndsWith("jpg")) && ((!path.ToLower().EndsWith("jpeg") && !path.ToLower().EndsWith("bmp")) && !path.ToLower().EndsWith("png")))
            {
                return str;
            }
            str = "<a target=_blank href=show_photo.aspx?filename=" + Server.UrlEncode(path) + "><img align=absMiddle border=0 src=thumb.aspx?filename=" + Server.UrlEncode(path);
            if (upDownMaximum != string.Empty)
            {
                str = str + "&upDownMaximum=" + upDownMaximum;
            }
            return (str + "></a>");
        }

    }
}
